package com.kws.merchant.service.impl;


import com.kws.common.security.auth.AuthUtil;
import com.kws.merchant.domain.MerchantTarget;
import com.kws.merchant.domain.Target;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.mapper.TargetMapper;
import com.kws.merchant.service.MerchantTargetService;
import com.kws.merchant.service.TargetService;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 商家-指标(Target)表服务实现类
 *
 * @author yxy
 * @since 2024-11-04 11:39:02
 */
@Service("targetService")
public class TargetServiceImpl extends ServiceImpl<TargetMapper, Target> implements TargetService {

    @Resource
    private TargetMapper targetMapper;
    @Autowired
    private MerchantTargetService merchantTargetService;

    /**
     * 分页查询列表
     */
    @Override
    public Page<Target> pageList(Target target) {
        Page<Target> page = new Page<>(0, 10);
        LambdaQueryWrapper<Target> queryWrapper = Wrappers.lambdaQuery();

        return this.page(page, queryWrapper);
    }

    /**
     * 查询商家指标列表
     * @return
     */
    @Override
    public  List<Target> getMerchantByList() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        //查询商家相关指标,如果没有就默认为所有指标
        List<Target> targetList=targetMapper.getMerchantByList(sysUser.getUserId());
        if (targetList.size()==0){
            targetList=this.list();
        }
        return targetList;
    }

    /**
     * 新增商家指标
     * @param idList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object addMerchantTarget(List<Long> idList) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        merchantTargetService.remove(Wrappers.<MerchantTarget>lambdaQuery().eq(MerchantTarget::getMerchantId,sysUser.getUserId()));
        ArrayList<MerchantTarget> merchantTargets = new ArrayList<>();
        idList.forEach(x->{
            MerchantTarget merchantTarget = new MerchantTarget();
            merchantTarget.setMerchantId(sysUser.getUserId());
            merchantTarget.setTargetId(x);
            merchantTargets.add(merchantTarget);
        });
        return merchantTargetService.saveBatch(merchantTargets);
    }


}
